package cn.weixin.song.model;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cn.weixin.song.model.base.BaseActivityShareRecord;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.jcbase.core.model.Condition;
import com.jcbase.core.model.Operators;
import com.jcbase.core.view.InvokeResult;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

/**
 * Generated by JFinal.
 */
@SuppressWarnings("serial")
public class ActivityShareRecord extends BaseActivityShareRecord<ActivityShareRecord> {
	public static final ActivityShareRecord dao = new ActivityShareRecord();
	
	public InvokeResult addActivityShareRecord(Activity activity,
			String openid, Integer type) {
		User user=User.dao.getUser(activity.getAppId(), openid);
		if(type!=1&&type!=2){
			return InvokeResult.failure("type非法");
		}
		Map<String,Object> data=Maps.newHashMap();
		data.put("add_count",0);
		if(user!=null&&activity!=null){
			if(!hasShare(user.getId(), activity.getId(), type)){//首次分享
				ActivityUserPlay activityUserPlay=ActivityUserPlay.dao.getActivityUserPlay(user.getId(), activity.getId());
				if(activityUserPlay!=null){
					activityUserPlay.setLeftPlayCount(activityUserPlay.getLeftPlayCount()+1);
					activityUserPlay.update();
					data.put("add_count",1);
				}
			}
			ActivityShareRecord activityShareRecord=new ActivityShareRecord();
			activityShareRecord.setUid(user.getId());
			activityShareRecord.setShareTime(new Date());
			activityShareRecord.setActivityId(activity.getId());
			activityShareRecord.setType(type);
			activityShareRecord.save();
		}
		return InvokeResult.success(data);
	}
	/**
	 * 判断是否已经分享过
	 */
	public boolean hasShare(int uid,int activityId,int type){
		Set<Condition> conditions=Sets.newHashSet();
		conditions.add(new Condition("uid",Operators.EQ,uid));
		conditions.add(new Condition("activity_id",Operators.EQ,activityId));
		conditions.add(new Condition("type",Operators.EQ,type));
		return this.getCount(conditions)>0?true:false;
	}
	
	public Page<Record> getActivityShareRecordPage(int page, int rows,
			Integer aid, String keyword, String orderbyStr) {
		
		String select="select asr.*,u.mobilephone,u.id as uid,u.nickname";
		StringBuffer sqlExceptSelect=new StringBuffer("from activity_share_record asr left join user u on asr.uid=u.id  where asr.activity_id=?");
		List<Object> paras=Lists.newArrayList();
		paras.add(aid);
		if(StrKit.notBlank(keyword)){
			sqlExceptSelect.append(" and (u.mobilephone like ? or u.nickname like ?)");
			paras.add("'%"+keyword+"%'");
			paras.add("'%"+keyword+"%'");
		}
		if(StrKit.notBlank(orderbyStr)){
			sqlExceptSelect.append(" "+orderbyStr);
		}
		return Db.paginate(page, rows, select, sqlExceptSelect.toString(), paras.toArray());
	}
}
